<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  
  <link rel="stylesheet" href="/public/asset/bootstrap.min.css">
  <link rel="stylesheet" href="/public/asset/bootstrap-icons-141.css">
  <link rel="stylesheet" href="/public/asset/style.css">
  
  <script src="/public/asset/jquery.min.js"></script>
  <script src="/public/asset/dayjs.min.js"></script>
  <script src="/public/asset/bootstrap.bundle.min.js"></script>
  <script src="/public/asset/util.js"></script>
  
  <title>Deny Islands - iPelago</title>
  <style>
    .bi {
      cursor: pointer;
    }
    .bi-x:hover {
      color: red;
    }
  </style>
</head>
<body>
  <div id="root" class="container" style="max-width: 775px; min-width: 400px;"></div>

<script>

const Loading = CreateLoading();
const Alerts = CreateAlerts();
const Logs = CreateLogs();

const TitleArea = {
  view: () => m('div').addClass('d-flex justify-content-between align-items-center my-5').append([
    m('div').attr({id:'title'}).addClass('display-6').text('Deny List (黑名单)'),
    m('a').attr({href:'/public/home.html',title:'home'}).addClass('btn btn-outline-dark').append(
      m('i').addClass('bi bi-house-door')
    ),
  ]),
};

const SubmitBtn = cc('button');
const Addresses = cc('textarea');
const AddressesArea = cc('div', null, [
  m('p').text('在此添加你想屏蔽的小岛地址，该功能主要用来防止批量订阅时订阅到不想看的小岛。'),
  m(Addresses).addClass('form-control').on('input', () => {
    const self = $(Addresses.id);
    self.css('height', self.prop('scrollHeight'));
  }),
  m('p').addClass('text-center my-3').append(
    m(SubmitBtn).text('Submit').attr({type:'button'}).addClass('btn btn-primary')
  ),
]);

const DenyList = cc('ul');

DenyList.view = () => m('ul')
  .attr({id:DenyList.raw_id}).addClass('list-group list-group-flush');

DenyList.append = (islands) => {
  islands.forEach((addr) => {
    const item = CreateItem(addr);
    $(DenyList.id).append(m(item));
    item.init();
  });
};

$('#root').append([
  m(TitleArea),
  m(Alerts).addClass('my-3'),
  m(AddressesArea),
  m(Logs),
  m(Loading),
  m(DenyList).addClass('my-5'),
]);

init();

function init() {
  $(SubmitBtn.id).click(() => {
    disable(SubmitBtn.id);

    const addresses = $(Addresses.id).val().split('\n')
      .map(item => item.trim())
      .filter(item => item.length > 0);

    denyIslands(addresses);
    // 在 followIslands 之后如果有代码，会立即执行，不会等待 followIslands。
  });

  ajax({method:'GET',url:'/api/get-denylist',alerts:Alerts},
      (islands) => {
        if (!islands || islands.length == 0) {
          return;
        }
        DenyList.append(islands);
      }, null, () => {
        $(Loading.id).hide();
      });
}

async function denyIslands(islands) {
  for (let i=0; i<islands.length; i++) {
    try {
      await denyOne(islands[i]);
      Logs.insert('success', '屏蔽成功: ' + islands[i]);
    } catch (error) {
      if (error.indexOf("UNIQUE constraint failed: denylist.address") >= 0) {
        // 忽略已屏蔽的小岛
        Logs.insert('success', '已在屏蔽名单中: ' + islands[i]);
        continue;
      }
      Logs.insert('danger', `${islands[i]} ${error}`);
    }
  }
  Logs.insert('primary', '处理完成，结果如下所示：');
  enable(SubmitBtn.id);
}

function denyOne(islandAddr) {
  return new Promise((resolve, reject) => {
    const timeout = window.setTimeout(() => {
      reject(Error('timeout'));
    }, 2*1000);

    const body = new FormData();
    body.set('address', islandAddr);
    ajax({method:'POST',url:'/api/deny-island',body:body}, () => {
      // onSuccess
      resolve();
    }, (errMsg) => {
      // onError
      reject(errMsg);
    }, () => {
      // onAlways
      window.clearTimeout(timeout);
    });
  });
}

function CreateItem(addr) {
  const ItemAlerts = CreateAlerts();
  const self = cc('li', null, [
    m('span').text(addr).addClass('Address'),
    m('i').addClass('bi bi-x ms-1').attr({title:'remove from list'}),
    m(ItemAlerts),
  ]);
  self.init = () => {
    const del_btn_id = `${self.id} .bi-x`;
    $(del_btn_id).click(() => {
      const body = new FormData();
      body.set('address', addr);
      ajax({method:'POST',url:'/api/remove-deny',alerts:ItemAlerts,buttonID:del_btn_id,body:body},
          () => {
            $(self.id).find('.Address').hide();
            $(del_btn_id).hide();
            ItemAlerts.insert('success', '已解除屏蔽: ' + addr);
          });
    });
  };
  return self;
}

</script>
</body>
</html>